package cn.green.mapper.model.impls.field;

import cn.green.mapper.model.impls.table.EntityTableMapper;
import cn.green.mapper.model.FieldColumnMapper;
import cn.green.mapper.store.EntityTableMapperStore;
import cn.green.mvc.entity.OrmTableEntity;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @author wang.yishu
 * @version 1.0
 * @className OneToOneFieldColumnMapper
 * @description 一对一类型的映射
 * @date 2025/7/23 10:20
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class OneToOneFieldColumnMapper extends FieldColumnMapper {

    protected Class<?> mapperClass;

    @Override
    public void setFieldValue(JSONObject row, OrmTableEntity entity) throws Exception {
        if (row == null) {
            return;
        }
        JSONObject object = row.getJSONObject(this.column.getFieldName());
        if (object == null) {
            return;
        }
        if (this.mapperClass == null) {
            return;
        }
        EntityTableMapper entityTableMapper = EntityTableMapperStore.get(this.mapperClass);
        this.field.setAccessible(true);
        if (entityTableMapper == null) {
            if (this.mapperClass.equals(JSONObject.class)) {
                this.field.set(entity, object);
            }
            return;
        }
        OrmTableEntity mapperEntity = entityTableMapper.toEntity(object);
        if (mapperEntity == null) {
            return;
        }
        this.field.set(entity, mapperEntity);
    }

    @Override
    public void setColumnValue(JSONObject row, OrmTableEntity entity) throws Exception {
        this.field.setAccessible(true);
        Object object = this.field.get(entity);
        if (object == null) {
            return;
        }
        if (this.mapperClass == null) {
            return;
        }
        EntityTableMapper entityTableMapper = EntityTableMapperStore.get(this.mapperClass);
        if (entityTableMapper == null) {
            if (this.mapperClass.equals(JSONObject.class)) {
                row.put(this.column.getFieldName(), object);
            }
            return;
        }
        JSONObject json = entityTableMapper.toJson((OrmTableEntity) object);
        row.put(this.column.getFieldName(), json);
    }
}
